/*-
 * Copyright (c) 2009 Jonathan Anderson
 * All rights reserved.
 *
 * WARNING: THIS IS EXPERIMENTAL SECURITY SOFTWARE THAT MUST NOT BE RELIED
 * ON IN PRODUCTION SYSTEMS.  IT WILL BREAK YOUR SOFTWARE IN NEW AND
 * UNEXPECTED WAYS.
 * 
 * This software was developed at the University of Cambridge Computer
 * Laboratory with support from a grant from Google, Inc. 
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */


#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>

#include <libcapsicum.h>
#include <libuserangel.h>

#include <iostream>

#include "TextEditor.h"

#include <QDebug>
#include <QFile>
#include <QMessageBox>

#include <fontconfig/fontconfig.h>
#include <xcb/xcb.h>


#include <dlfcn.h> // TODO: tmp


extern char **environ;


int sandbox(int argc, char *argv[])
{
	stdout = fdopen(fcntl(STDOUT_FILENO, F_DUPFD, 0), "w");
	stderr = fdopen(fcntl(STDERR_FILENO, F_DUPFD, 0), "w");

	printf("sandbox()\n"); fflush(stdout);
	if(getenv("DEBUG"))
	{
		printf("DEBUG set, pausing...\n");
		fflush(stdout);
		sleep(120);
	}

/*
	for(int i = 0; environ[i]; i++)
		printf("environ[%d]:\t%s\n", i, environ[i]);

	fflush(stdout);

	lc_fdlist_print(lc_fdlist_global(), 1);
*/
	bool result = FcInit();
	fflush(stdout);
	fflush(stderr);

	if(result) printf("FcInit() succeeded.\n");
	else printf("FcInit() failed.\n");
	fflush(stdout);

	//return 0;


	// get a file descriptor for our host
	struct lc_host *lchpp;
	if(lcs_get(&lchpp) < 0) err(EX_IOERR, "Error getting lc_host");

	int host;
	if(lcs_getsock(lchpp, &host) < 0) err(EX_IOERR, "Error in lcs_getsock()");

	// find the User Angel
	int32_t angel = -1;
	size_t angellen = 1;
	struct ua_datum *d = ua_recv(host, &angel, &angellen);

	if(!d) err(-1, "Received NULL datum");
	if(angellen != 1) err(-1, "Received %zu FDs, not 1", angellen);

	ua_set_client_name("Sandboxed Text Editor");
	ua_set(angel);



	// receive X file descriptor, Xauth data
	struct lc_fdlist *fdlist = lc_fdlist_global();

	int32_t Xfd = -1;
	if(lc_fdlist_lookup(fdlist, "org.freebsd.capsicum.textcap", "X", NULL,
	                    &Xfd, NULL) == -1)
		err(-1, "Error in lc_fdlist_lookup()");


	char display[20];
	sprintf(display, "fd://cap:%i", Xfd);
	setenv("DISPLAY", display, 1);


	d = ua_recv(host, NULL, 0);
	if(!d) err(-1, "Received NULL datum");

	size_t xauthnamelen = 50;
	char xauthname[xauthnamelen];
	if(ua_unmarshall_string(d, xauthname, &xauthnamelen) < 0)
		err(EX_IOERR, "Error unmarshalling Xauth name");

	d = ua_recv(host, NULL, 0);
	if(!d) err(-1, "Received NULL datum");

	size_t xauthdatalen = 50;
	char xauthdata[xauthdatalen];
	if(ua_unmarshall_string(d, xauthdata, &xauthdatalen) < 0)
		err(EX_IOERR, "Error unmarshalling Xauth data");

	xcb_auth_info_t xauthinfo;
	xauthinfo.namelen = xauthnamelen;
	xauthinfo.name = xauthname;
	xauthinfo.datalen = xauthdatalen;
	xauthinfo.data = xauthdata;

	xcb_auth_cache(&xauthinfo);



	d = ua_recv(host, NULL, 0);
	if(!d) err(-1, "Error receiving settings from host");

	size_t len = d->length;
	char buffer[len];
	if(ua_unmarshall_bytes(d, buffer, &len) < 0)
		err(-1, "Error unmarshalling settings");

	QByteArray settingBytes = QByteArray::fromRawData(buffer, len);
	QDataStream stream(settingBytes);

	QMap<QString,QVariant> settings;
	stream >> settings;

	qDebug() << settings.size() << " settings:";
	for(QMap<QString,QVariant>::Iterator i = settings.begin();
	    i != settings.end(); i++)
		qDebug() << i.key() << " " << i.value();


	//return 0;
	QApplication app(argc, argv);

	new TextEditor();
	fflush(stdout);
	fflush(stderr);
	return app.exec();
}

